package com.galeno.demo;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author galeno
 * @Title: 教师节Happy
 * @Description: 实现一个卡夫卡的消费者
 * @date 2021/9/1022:38
 */
public class Consumer {
    public static void main(String[] args) {
        String serverUrl = "galeno01:9092,galeno02:9092,galeno03:9092";
        Properties properties = new Properties();
        properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,serverUrl);
        properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"g01");
        properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"latest");

        // 一次拉取，最大数据量
        properties.setProperty(ConsumerConfig.FETCH_MAX_BYTES_CONFIG,"41943040");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        // 订阅一个或多个主题
        consumer.subscribe(Arrays.asList("first"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    // 拉取（消费）数据  （一次poll会拉取到一批record）

                    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));

                    for (ConsumerRecord<String, String> record : records) {
                        System.out.println(Thread.currentThread().getName()+","+record.key() + " , " + record.value() + " , " + record.partition() + " , " + record.offset());
                    }


                }

            }
        },"线程1").start();
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while(true) {
//                    // 拉取（消费）数据  （一次poll会拉取到一批record）
//                    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
//
//                    for (ConsumerRecord<String, String> record : records) {
//                        System.out.println(Thread.currentThread().getName()+","+ record.key() + " , " + record.value() + " , " + record.partition() + " , " + record.offset());
//                    }
//
//
//                }
//
//            }
//        },"线程2").start();




    }
}
